<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="问卷标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入问卷标题，不能为空，长度最大为255字符"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="问卷类型" prop="surveyType">
        <el-select v-model="queryParams.surveyType" placeholder="请选择问卷类型，1：内科问卷 2：外科问卷" clearable>
          <el-option
            v-for="dict in dict.type.survey_sys_survey_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="医院ID" prop="hosId">
        <el-input
          v-model="queryParams.hosId"
          placeholder="请输入医院ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医院名称" prop="hosName">
        <el-input
          v-model="queryParams.hosName"
          placeholder="请输入医院名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室ID" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入科室ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入科室名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生ID" prop="doctorId">
        <el-input
          v-model="queryParams.doctorId"
          placeholder="请输入医生ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['survey:surveyInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['survey:surveyInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['survey:surveyInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['survey:surveyInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="surveyInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="问卷ID" align="center" prop="surveyId" />
      <el-table-column label="问卷标题" align="center" prop="title" />
      <el-table-column label="问卷类型" align="center" prop="surveyType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.survey_sys_survey_type" :value="scope.row.surveyType"/>
        </template>
      </el-table-column>
      <el-table-column label="医院ID" align="center" prop="hosId" />
      <el-table-column label="医院名称" align="center" prop="hosName" />
      <el-table-column label="科室ID" align="center" prop="deptId" />
      <el-table-column label="科室名称" align="center" prop="deptName" />
      <el-table-column label="医生ID" align="center" prop="doctorId" />
      <el-table-column label="医生姓名" align="center" prop="doctorName" />
      <el-table-column label="问卷描述" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['survey:surveyInfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['survey:surveyInfo:remove']"
          >删除</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-search"
              @click="handleViewDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改问卷信息，存储问卷的基本信息，包括ID、标题、描述和时间戳对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问卷标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入问卷标题，不能为空，长度最大为255字符" />
        </el-form-item>
        <el-form-item label="问卷类型" prop="surveyType">
          <el-select v-model="form.surveyType" placeholder="请选择问卷类型，1：内科问卷 2：外科问卷">
            <el-option
              v-for="dict in dict.type.survey_sys_survey_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医院ID" prop="hosId">
          <el-input v-model="form.hosId" placeholder="请输入医院ID" />
        </el-form-item>
        <el-form-item label="医院名称" prop="hosName">
          <el-input v-model="form.hosName" placeholder="请输入医院名称" />
        </el-form-item>
        <el-form-item label="科室ID" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入科室ID" />
        </el-form-item>
        <el-form-item label="科室名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="医生ID" prop="doctorId">
          <el-input v-model="form.doctorId" placeholder="请输入医生ID" />
        </el-form-item>
        <el-form-item label="医生姓名" prop="doctorName">
          <el-input v-model="form.doctorName" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="问卷描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="问卷详情"
        :visible.sync="dialogVisible"
        width="50%"
        @close="handleClose"
    >
      <!-- 将问卷编辑组件放入弹出框中 -->
      <survey-form :form="form" :questionForm="questionForm" />
    </el-dialog>
  </div>
</template>

<script>
import { listSurveyInfo, getSurveyInfo, delSurveyInfo, addSurveyInfo, updateSurveyInfo } from "@/api/survey/surveyInfo";
import SurveyForm from "./template/SurveyForm.vue";
import {surveyQuestionBySurveyId} from "../../../api/survey/surveyInfo";

export default {
  name: "SurveyInfo",
  dicts: ['survey_sys_survey_type'],
  components: {
    SurveyForm  // 注册问卷编辑组件
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问卷信息，存储问卷的基本信息，包括ID、标题、描述和时间戳表格数据
      surveyInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        surveyType: null,
        hosId: null,
        hosName: null,
        deptId: null,
        deptName: null,
        doctorId: null,
        doctorName: null,
        description: null,
      },
      dialogVisible: false,  // 控制弹出框的显示与隐藏
      surveyData: [],  // 假设这里是从后端获取的问卷数据
      // 表单参数
      form: {},
      questionForm:[],
      // 表单校验
      rules: {
        title: [
          { required: true, message: "问卷标题", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async handleViewDetail(row) {
      try {
        // 等待异步请求完成，获取问卷数据
        const response = await surveyQuestionBySurveyId(row);

        // 处理返回的数据，构造 questionData
        let questionData = response.rows.map((question) => {
          return {
            id: question.questionId, // 使用后台的 questionId 作为唯一的 id
            sort: question.sort, // 排序字段，按索引 +1
            type: question.questionType, // 问题类型，如 'radio'、'checkbox' 等
            text: question.questionText, // 问题文本
            options: question.surveyOptionList
                .sort((a, b) => a.optionSort - b.optionSort)  // 按照 `optionSort` 字段排序选项
                .map(option => ({
                  optionId: option.optionId,
                  questionId: option.questionId,
                  optionText: option.optionText,
                  optionSort: option.optionSort  // 添加 optionSort 字段
                })), // 映射成包含 `optionId`, `questionId`, `optionText`, 和 `optionSort` 的对象
            selectedOptions: [] // 初始化用户选择的选项为空数组
          };
        });


        // 更新组件的状态
        this.questionForm = questionData; // 设置问题数据
        this.form = row;  // 设置问卷信息
        this.dialogVisible = true;  // 打开弹出框
      } catch (error) {
        console.error('获取问卷数据失败', error);  // 捕获并处理请求错误
        // 你可以在这里显示一个错误提示，告知用户请求失败
      }
    },
    handleClose() {
      this.dialogVisible = false;  // 关闭弹出框
      this.form = {};  // 可选：关闭时清空数据
    },
    /** 查询问卷信息，存储问卷的基本信息，包括ID、标题、描述和时间戳列表 */
    getList() {
      this.loading = true;
      listSurveyInfo(this.queryParams).then(response => {
        this.surveyInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        surveyId: null,
        title: null,
        surveyType: null,
        hosId: null,
        hosName: null,
        deptId: null,
        deptName: null,
        doctorId: null,
        doctorName: null,
        description: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.surveyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加问卷信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const surveyId = row.surveyId || this.ids
      getSurveyInfo(surveyId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改问卷信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.surveyId != null) {
            updateSurveyInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSurveyInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const surveyIds = row.surveyId || this.ids;
      this.$modal.confirm('是否确认删除问卷信息? 编号为"' + surveyIds + '"的数据项？').then(function() {
        return delSurveyInfo(surveyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('survey/surveyInfo/export', {
        ...this.queryParams
      }, `surveyInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
